import React, { Component } from 'react'
import styles from './Links.module.scss'
import goToTop from './../../images/backtop.png'
import api from '../../serve/api';

var timer = null;

export default class Links extends Component {

  constructor(props) {
    super(props)
    this.state = {
      types: [],
      paterners: [],
      paternerIndex: 0,
    }
  }

  goToTop() {
    cancelAnimationFrame(timer);
    timer = requestAnimationFrame(function fn(){
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
            window.scrollBy(0, -200);
            timer = requestAnimationFrame(fn);
        } else {
            cancelAnimationFrame(timer);
        }    
    })
  }

  componentDidMount() {
    // this.getPaterner()
    this.getAllType()
  }

  async getAllType() {
    const { code, result } = await api.listPaternerTypeAll()
    if (code !== '000000') {
      return
    }
    this.setState({
      types: result
    })
    if (result.length > 0) {
      const first = result[0]
      this.getPaterner(first.id)
    }
  }

  async getPaterner(typeId) {
    const data = await api.listPaterner({ typeId, page: 1, pageSize: 9999 })
    if (data && data.code === '000000') {
      this.setState({
        paterners: data.result || []
      })
    }
  }

  onPaterner(id, index) {
    this.setState({
      paternerIndex: index
    })
    this.getPaterner(id)
  }

  render() {
    const { paterners, paternerIndex, types } = this.state
    return (
      <div className={styles.links}>
        <div className={styles.header}>
          <div className={styles.div}>
            <span className={styles.friend} style={paternerIndex === 0 ? { color: '#b0200c'} : {}} 
            onClick={() => this.onPaterner(types[0].id, 0)}>
              {(types[0] && types[0].name) || ''}
            </span>
            <p className={styles.line}></p>
            <span className={styles.paterner} style={paternerIndex === 1 ? { color: '#b0200c'} : {}} 
            onClick={() => this.onPaterner(types[1].id, 1)}>
              {(types[0] && types[1].name) || ''}
            </span>
          </div>
        </div>
        <div className={styles.links_list}>
          {paterners.map((item, index) => {
            return (
              <a key={index} href={item.url} target="_blank" rel="noopener noreferrer">
                <img key={index} src={item.img || ''} alt="" />
              </a>
            )
          })}
        </div>
        {/* <div className={styles.go_to_top}>
          <img src={goToTop} alt="" onClick={() => this.goToTop()}/>
        </div> */}
      </div>
    )
  }
}
